import axios from "axios";
import StorageService from "@/store/dataStore";
//获取当前页面路由
import getPathAddress from "@/router/index";



const instance = axios.create({ timeout: 6000 });


/**
 * 地址
 */
/* 根据环境不同 选择url*/
let BackUrl = null;
let BasiUrl = process.env.NODE_ENV;
console.log("环境" + BasiUrl);
/* 开发环境*/
if (BasiUrl === "development") {
    BackUrl = "http://192.168.1.9:29113/";
} else if (BasiUrl === "production") {
    /* 打包环境*/
    BackUrl = "https://cg.zhipu-china.com/g1/t/gsi/";
}
/**
 * 添加请求拦截器
 */
instance.interceptors.request.use((config) => {
    //网络设置
    config.baseURL = BackUrl
    // 获取本地存储数据
    const localDataValue = StorageService.localData.token;
    //请求头
    config.headers = {
        ...config.headers,
        "Content-Type": "application/json",
    };
    //当前路径
    const CurrentPath = getPathAddress.currentRoute.value.name
    //判断
    if (localDataValue && CurrentPath !== "login") {
        //请求头
        config.headers = {
            "Authorization": "Bearer " + localDataValue, //如果要求携带在请求头中
        }
    }
    return config;
}, error => {
    Promise.reject(error);
});

/**
 * 添加响应拦截器
 */
instance.interceptors.response.use(
    (resp) => {

        if (resp.data.status > 200) {
            return Promise.reject(resp.data?.msg);
        }
        return resp.data;
    },
    (err) => {
        if (err.response && err.response.status >= 400) {
            return Promise.reject(
                err.response?.data.msg.length > 15
                    ? `响应状态码${err.response?.status},详情请查看network`
                    : err.response.data.msg
            );
        }
        return Promise.reject("网络异常!!!");
    }
);

export default instance;
